using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[Serializable]
public class CapsuleColliderUtility
{
   [SerializeField]
   private CapsuleColliderData capsuleColliderData;

   public CapsuleColliderData CapsuleColliderData
   {
      get => capsuleColliderData;
      set => capsuleColliderData = value;
   }

   [SerializeField]
   private DefaultColliderData defaultColliderData;

   public DefaultColliderData DefaultColliderData
   {
      get => defaultColliderData;
      set => defaultColliderData = value;
   }

   [SerializeField]
   private SlopeData slopeData;

   public SlopeData SlopeData
   {
      get => slopeData;
      set => slopeData = value;
   }

   public void Initialize(GameObject gameObj)
   {
      if (CapsuleColliderData != null && CapsuleColliderData.Collider != null)
         return;

      CapsuleColliderData = new CapsuleColliderData();
      
      CapsuleColliderData.Initialize(gameObj);
   }
   
   public void CalculateCapsuleColliderDismensions()
   {
      SetCapsuleColliderRadius(DefaultColliderData.Radius);
      
      SetCapsuleColliderHeight(DefaultColliderData.Height * (1 - SlopeData.StepHeightPercentage));
      
      RecalculateCapsuleColliderCenter();
       
      // 处理胶囊碰撞体高度小于球体直径的情况
      float halfColliderHeight = CapsuleColliderData.Collider.height / 2;
      if (halfColliderHeight < CapsuleColliderData.Collider.radius)
      {
         SetCapsuleColliderRadius(halfColliderHeight);
      }
      
      CapsuleColliderData.UpdateColliderData();
   }

   public void SetCapsuleColliderRadius(float radius)
   {
      CapsuleColliderData.Collider.radius = radius;
   }

   public void SetCapsuleColliderHeight(float height)
   {
      CapsuleColliderData.Collider.height = height;
   }
   
   public void RecalculateCapsuleColliderCenter()
   {
      float heightDiff = DefaultColliderData.Height - CapsuleColliderData.Collider.height;
      CapsuleColliderData.Collider.center = new Vector3(0, DefaultColliderData.CenterY + heightDiff / 2f, 0);
   }
}
